<template>
  <div v-show="!isMain && isAdd" class="add-inspect-plan">
    <div class="add-inspect-plan-wrapper">
      <px-scrollbar ref="scrollbarRef" class="add-inspect-plan-content" @scroll="handleScroll">
        <px-button ref="basicsRef" style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage"
          >返回</px-button
        >
        <px-form
          ref="formRef"
          :inline="false"
          :model="formValue"
          :rules="rules"
          label-position="right"
          label-width="150px"
          :validate-on-rule-change="false"
        >
          <div>
            <EditDropDown dropdownTitle="基本信息">
              <template v-slot:content>
                <div class="block w-[100%]">
                  <px-row :gutter="16">
                    <px-col :span="12">
                      <px-form-item label="巡检计划编号" prop="planNo">
                        <px-input v-model="formValue.planNo" disabled />
                      </px-form-item>
                    </px-col>
                    <px-col :span="12">
                      <px-form-item label="巡检计划名称" prop="planName">
                        <px-input
                          v-model="formValue.planName"
                          placeholder="请输入巡检计划名称"
                          maxlength="50"
                          @blur="formValue.planName = $event.target.value.trim()"
                        />
                      </px-form-item>
                    </px-col>
                  </px-row>
                  <px-row :gutter="16">
                    <px-col :span="12">
                      <!-- 地块 -->
                      <FactoryArea :factoryArea="formValue.factoryAreaCode" :isRequired="true" @changeFactoryArea="changeFactoryArea" />
                    </px-col>
                    <px-col :span="12">
                      <px-form-item label="任务分配" prop="checkGroupCode">
                        <px-select
                          v-model="formValue.checkGroupCode"
                          clearable
                          filterable
                          placeholder="请选择巡检组"
                          style="width: 100%"
                          @change="changeCheckGroupCode"
                        >
                          <px-option v-for="item in checkGroupList" :key="item.id" :label="item.name" :value="item.code" />
                        </px-select>
                      </px-form-item>
                    </px-col>
                  </px-row>
                  <px-row :gutter="16">
                    <px-col :span="12">
                      <px-form-item label="建议工作天数" prop="recommendDay">
                        <px-input-number v-model="formValue.recommendDay" placeholder="请输入建议工作天数" :min="1" :max="999" />
                      </px-form-item>
                    </px-col>
                  </px-row>
                  <px-row :gutter="16">
                    <px-col :span="24">
                      <px-form-item label="说明" prop="description">
                        <px-input v-model="formValue.description" placeholder="请输入巡检计划说明信息" type="textarea" />
                      </px-form-item>
                    </px-col>
                  </px-row>
                </div>
              </template>
            </EditDropDown>
          </div>
          <div ref="contentRef">
            <EditDropDown dropdownTitle="巡检内容">
              <template v-slot:content>
                <div class="block w-[100%]">
                  <px-row :gutter="16">
                    <px-col :span="12">
                      <CheckArea
                        :checkArea="formValue.checkArea"
                        :isRequired="true"
                        :fac-code="formValue.factoryAreaCode"
                        @changeCheckArea="changeCheckArea"
                      />
                    </px-col>
                    <px-col :span="12">
                      <px-form-item label="巡检内容" prop="checkType">
                        <px-radio-group v-model="formValue.checkType" @change="checkTypeChange">
                          <px-radio label="equipment">设备巡检</px-radio>
                          <px-radio label="environment">环境巡检</px-radio>
                        </px-radio-group>
                      </px-form-item>
                    </px-col>
                  </px-row>
                  <px-row :gutter="16">
                    <px-col :span="24">
                      <px-form-item label="巡检规则" prop="tableData" class="_form-rules">
                        <px-button type="primary" ghost class="mb-[10px]" @click="handleSelectRules">选择巡检规则</px-button>

                        <InspectRulesTable :table-data="tableData" :tableColumns="tableColumns" :total="0" class="w-[100%]" @del="deleteSelected" />
                      </px-form-item>
                    </px-col>
                  </px-row>
                </div>
              </template>
            </EditDropDown>
          </div>
          <div ref="periodRef">
            <EditDropDown dropdownTitle="执行周期">
              <template v-slot:content>
                <ExecutionCycle :taskList="taskList" :form-value="formValue" @change="handelExecutionCycleChange" />
              </template>
            </EditDropDown>
          </div>
          <div ref="equipRef">
            <EditDropDown v-show="formValue.checkType === 'equipment'" dropdownTitle="设备巡检">
              <template v-slot:content>
                <div class="w-[100%]">
                  <px-row :gutter="16">
                    <px-col :span="24">
                      <px-button
                        :disabled="!formValue.factoryAreaCode || !formValue.checkArea || typeCodeList.length === 0"
                        type="primary"
                        ghost
                        class="mb-[10px]"
                        @click="handleSelectEquip"
                        >选择设备</px-button
                      >

                      <InspectRulesTable
                        :table-data="tableEqiupSelected"
                        :tableColumns="tableEqiupColums"
                        :total="0"
                        :hasDrag="true"
                        class="w-[100%]"
                        @on-drag="tableEqiupDrag"
                        @del="deleteEquipSelected"
                      />
                    </px-col>
                  </px-row>
                </div>
              </template>
            </EditDropDown>
          </div>
        </px-form>
      </px-scrollbar>
      <div class="info-form-btns">
        <px-button @click="backMainPage">取消</px-button>
        <px-button v-if="(!planNo || formValue.planStatus == 1) && loading !== 'draft'" type="primary" ghost @click="handleDraft(formRef)"
          >保存草稿</px-button
        >
        <px-button v-else-if="loading == 'draft'" type="primary" ghost loading>保存草稿</px-button>
        <px-button v-if="loading !== 'submit'" type="primary" @click="handleSubmit(formRef)">发布巡检计划</px-button>
        <px-button v-else-if="loading == 'submit'" type="primary" ghost loading>发布巡检计划</px-button>
      </div>
    </div>
    <WidgetRouter ref="widgetRef" :router-list="routerList" :scrollbar-ref="scrollbarRef" :scroll-top="scrollTop" />
    <SelectInspectRules
      v-model:is-view="isDialogView"
      :facCode="formValue.factoryAreaCode"
      :check-type="[formValue.checkType]"
      :check-area="formValue.checkArea"
      @select-items="selectTreeItems"
    />
    <SelectInspectEquip
      v-model:is-view="isAddEquip"
      :checkArea="formValue.checkArea"
      :facCode="formValue.factoryAreaCode"
      :typeCodeList="typeCodeList"
      @select-items="selectEquipItems"
    />
  </div>
  <BackAlarmDialog
    v-model:visible="backVisible"
    :hasDraft="!planNo || formValue.planStatus == 1"
    @back="dataInit"
    @draft="handleDraft(formRef)"
    @save="handleSubmit(formRef)"
  />
</template>
<script setup lang="ts">
import { getByPlanNo, getGroupList, getInspectPlanCode, publicInspectPlan, saveInspectPlan } from "@/api/erc/inspectPlan";
import { useBeforeRouteLeave } from "@/hooks/useBeforeRouteLeave";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { cloneDeep, debounce } from "@pureadmin/utils";
import { PxMessage } from "px-ui";
import { computed, onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import { CheckArea, ExecutionCycle, FactoryArea, WidgetRouter } from "../../components/index";
import { TableItem } from "../../types";
import InspectRulesTable from "./InspectRulesTable.vue";
import SelectInspectEquip from "./SelectInspectEquip.vue";
import SelectInspectRules from "./SelectInspectRules.vue";
import BackAlarmDialog from "./backAlarmDialog.vue";

const loading = ref("");

const tableColumns = ref<TableItem[]>([
  { prop: "expend", minWidth: "55", fixed: "left" },
  { prop: "checkRuleNo", label: "规则编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "checkRuleName", label: "巡检规则名称", minWidth: "160", showOverflowTooltip: true },
  { prop: "facName", label: "地块", minWidth: "160", showOverflowTooltip: true },
  { prop: "eqpTypeName", label: "设备类型/巡检区域", minWidth: "160", showOverflowTooltip: true },
  { prop: "ruleTypeName", label: "规则类型", minWidth: "160", showOverflowTooltip: true },
  // { prop: "recommendDay", label: "建议工作天数", minWidth: "160", showOverflowTooltip: true },
  { prop: "operate", minWidth: "55", label: "操作", showOverflowTooltip: true, align: "center" }
]);

const tableEqiupColums = ref<TableItem[]>([
  { prop: "drag", minWidth: "60" },
  { prop: "eqpId", label: "设备编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "eqpName", label: "设备名称", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  {
    prop: "typeNameAll",
    label: "设备系统",
    minWidth: "160",
    showOverflowTooltip: true,
    customFun: row => {
      if (row) {
        const strArr = row.split("/");
        if (strArr.length > 1) {
          strArr.pop();
          if (strArr.length > 1) {
            return strArr.join("/");
          } else {
            return strArr.join("");
          }
        } else {
          return row;
        }
      } else {
        return "-";
      }
    }
  },
  { prop: "typeName", label: "设备类型", minWidth: "160", showOverflowTooltip: true },
  { prop: "specification", label: "设备型号", minWidth: "160", showOverflowTooltip: true },
  { prop: "positionNameAll", label: "安装位置", minWidth: "160", showOverflowTooltip: true },
  { prop: "operate", minWidth: "55", label: "操作", showOverflowTooltip: true, fixed: "right" }
]);
const isMain = defineModel("isMain");
const isAdd = defineModel("isAdd");
const planNo = defineModel("planNo");
const isCopy = defineModel("isCopy");
const backVisible = ref(false);
//form表单相关
const formRef = ref();
let formDataTmpl = {
  planNo: "",
  planName: "",
  planStatus: 0,
  execType: "1", //执行方式 1-固定时间,2-周期时间
  execStartDate: "",
  execEndDate: "",
  execDuration: 1,
  execDurationUnit: "DAY",
  extendDuration: 1,
  extendDurationUnit: "DAY",
  factoryAreaCode: "",
  checkArea: "",
  checkGroupCode: "",
  cyclePerNum: 0,
  cyclePerUnit: "DAY",
  cycleValue: "",
  cycleTime: "8",
  taskCreateTime: 1,
  description: "",
  eqpRelationList: [],
  checkRuleNos: [],
  createTaskImmediately: 0,
  checkType: ""
};
const formValue = ref(cloneDeep(formDataTmpl));

//1-准点生成,2-提前10分钟,3-提前30分钟,4-提前1小时,5-提前1天
const taskList = [
  { value: 1, label: "准点生成" },
  { value: 5, label: "提前一天" },
  { value: 6, label: "提前一个月" },
  { value: 7, label: "提前三个月" }
];
const validateRulesTable = (rule: any, value: any, callback: any) => {
  if (!tableData.value || tableData.value?.length === 0) {
    callback(new Error("请选择巡检规则"));
  } else {
    callback();
  }
};
const rules = reactive({
  planNo: [{ required: true, trigger: "blur" }],
  planName: [
    {
      required: true,
      message: "请输入巡检计划名称",
      trigger: "blur"
    }
  ],
  checkGroupCode: [
    {
      required: true,
      message: "请选择巡检组",
      trigger: "change"
    }
  ],
  tableData: [
    //需要自定义规则
    {
      required: true,
      validator: validateRulesTable,
      trigger: "blur"
    }
  ],
  execType: [
    //需要自定义规则
    {
      required: true,
      message: "请选择执行方式",
      trigger: "change"
    }
  ],
  execStartDate: [
    //需要自定义规则
    {
      required: true,
      message: "请选择开始时间",
      trigger: "change"
    }
  ],
  execEndDate: [
    //需要自定义规则
    {
      required: true,
      message: "请选择结束时间",
      trigger: "change"
    }
  ],
  execDuration: [
    {
      required: true,
      message: "请选择执行时长",
      trigger: "blur"
    }
  ],
  taskCreateTime: [
    {
      required: true,
      message: "请选择任务生成并提醒时间",
      trigger: "change"
    }
  ],
  checkType: [
    {
      required: true,
      message: "请选择巡检内容",
      trigger: "change"
    }
  ]
});
const checkGroupList = ref([]); //任务分配下拉

const isAddEquip = ref(false);

const isDialogView = ref(false);
//折叠面板ref
const widgetRef = ref();
const basicsRef = ref(null);
const contentRef = ref(null);
const periodRef = ref(null);
const equipRef = ref(null);
//右侧滚动导航
const scrollbarRef = ref(null);
const routerList = ref([]);
const scrollTop = ref();
// 巡检规则table
const tableData = ref([]);
//选择设备table
const tableEqiupSelected = ref([]);
//初始化数据，用于判断是否有数据变更
let initData = "";
//刷新，关闭等未保存提示
const { setMessage, setIsFormDirty } = useBeforeRouteLeave();

//查询条件
watch(
  () => isAdd.value,
  async () => {
    setMessage("内容未保存，确认退出新建巡检计划吗？");
    if (isAdd.value) {
      setTimeout(() => {
        formRef?.value.clearValidate();
      }, 0);
      if (!planNo.value) {
        const planNo = await getInspectPlanCode();
        formValue.value.planNo = planNo;
      } else {
        let detail: { [key in string] } = await getByPlanNo({ planNo: planNo.value });
        detail.execType = String(detail.execType);
        const { checkRuleList, eqpList } = detail as any;
        tableData.value = checkRuleList?.length > 0 ? checkRuleList : [];
        tableEqiupSelected.value = eqpList?.length > 0 ? eqpList : [];
        formValue.value = detail;
        if (!formValue.value.checkType) {
          formValue.value.checkType = "";
        } else {
          formValue.value.checkType = detail.checkType[0];
        }
        if (isCopy.value) {
          const planNo = await getInspectPlanCode();
          formValue.value.planNo = planNo;
          formValue.value.planName = "";
          formValue.value.execStartDate = "";
          formValue.value.execEndDate = "";
          formValue.value.planStatus = 1;
          delete formValue.value.id;
        }
        delete formValue.value.eqpList;
      }
      setIsFormDirty(true);
      saveInitData();
    } else {
      planNo.value = "";
      setIsFormDirty(false);
    }
  }
);
watch(tableData, () => {
  if (tableData.value.length > 0) {
    formRef?.value.clearValidate("tableData");
  }
});
function backMainPage() {
  if (initData === JSON.stringify(formValue.value)) {
    dataInit();
  } else {
    backVisible.value = true;
  }
}
function dataInit() {
  isAdd.value = false;
  isMain.value = true;
  resetForm();
  planNo.value = "";
  isCopy.value = false;
  //返回时要重置滚动条
  scrollTop.value = 0;
  scrollbarRef.value.setScrollTop(0);
  initData = "";
  loading.value = "";
}
function saveInitData() {
  try {
    initData = JSON.stringify(formValue.value);
  } catch (error) {
    console.error(error);
  }
}
//表单项相关事件
function changeCheckGroupCode() {}
//reset表单
const resetForm = () => {
  if (!formRef?.value) return;
  formRef.value.resetFields();
  formValue.value = cloneDeep(formDataTmpl);
  tableData.value = [];
  tableEqiupSelected.value = [];
};
//表单提交
async function handleSubmit(formEl) {
  if (!formEl) return;

  await formEl.validate(async valid => {
    if (valid) {
      transformFormToSave();
      if (!tableEqiupSelected.value.length && formValue.value?.checkType === "equipment") {
        PxMessage.warning("请选择设备");
        return;
      }
      loading.value = "submit";
      try {
        const { checkType, ...others } = formValue.value;
        await publicInspectPlan({ ...others, checkType: checkType ? [checkType] : [] });
        saveInitData();
        backMainPage();
      } catch (e) {
        loading.value = "";
      }
    } else {
    }
  });
}

async function handleDraft(formEl) {
  if (!formEl) return;
  formEl.clearValidate();
  formEl.validateField("factoryAreaCode", async valid => {
    if (!valid) return;
    transformFormToSave();
    formValue.value.planStatus = 1; //草稿状态
    loading.value = "draft";
    try {
      const { checkType, ...others } = formValue.value;
      await saveInspectPlan({ ...others, checkType: checkType ? [checkType] : [] });
      saveInitData();
      backMainPage();
    } catch (e) {
      loading.value = "";
    }
  });
}
function transformFormToSave() {
  formValue.value.checkRuleNos = extractValuesByKey(tableData.value, "checkRuleNo");
  formValue.value.eqpRelationList = tableEqiupSelected.value.map((item, index) => {
    const { eqpId } = item;
    return { eqpId, sort: index, planNo: formValue.value.planNo };
  });
}
function extractValuesByKey(array, key) {
  const result = [];
  for (const obj of array) {
    if (obj.hasOwnProperty(key)) {
      result.push(obj[key]);
    }
  }
  return result;
}
//右侧滚动导航相关函数
const handleScroll = debounce(({ scrollTop: curScrollTop }) => {
  scrollTop.value = curScrollTop;
}, 200);

function scrollInit() {
  let routerName = "基本信息,巡检内容,执行周期,设备巡检";
  let routerRefs = [basicsRef, contentRef, periodRef, equipRef];
  routerList.value = routerName.split(",").map((item, index) => ({ ref: routerRefs[index], name: item }));
}
function tableEqiupDrag(evt) {
  const oldItem = tableEqiupSelected.value[evt.oldIndex];
  tableEqiupSelected.value.splice(evt.oldIndex, 1);
  tableEqiupSelected.value.splice(evt.newIndex, 0, oldItem);
}
const changeCheckArea = val => {
  if (val && val.length > 0) {
    // const codes = Array.from(new Set([].concat(...val))).join(",");
    // formValue.value.checkArea = codes;
    formValue.value.checkArea = val
      .map(item => {
        const ind = item.length - 1;
        return item[ind];
      })
      .join(",");
  } else {
    formValue.value.checkArea = "";
  }
  if (formValue.value?.checkType === "environment") {
    tableData.value = [];
  }
  tableEqiupSelected.value = [];
};
function changeFactoryArea(val) {
  formValue.value.factoryAreaCode = val;
  tableEqiupSelected.value = [];
  tableData.value = [];
  formValue.value.checkArea = "";
}
function handleSelectRules() {
  if (!formValue.value.factoryAreaCode || !formValue.value.checkType) {
    formRef?.value.validateField("factoryAreaCode");
    formRef?.value.validateField("checkType");
    if (formValue.value?.checkType === "environment") {
      formRef?.value.validateField("inspectArea");
    } else {
      formRef?.value.clearValidate("inspectArea");
    }
  } else {
    isDialogView.value = true;
  }
}
function checkTypeChange() {
  tableData.value = [];
  tableEqiupSelected.value = [];
  scrollInit();
}
function handleSelectEquip() {
  isAddEquip.value = true;
}
//巡检规则
function selectTreeItems(val) {
  tableData.value = mergeAndDeduplicate(tableData.value, val, "id");
}
const typeCodeList = computed(() => {
  return tableData.value.reduce((pre, cur) => {
    return [...pre, cur.eqpTypeCode];
  }, []);
});
//设备选择

function selectEquipItems(val) {
  tableEqiupSelected.value = mergeAndDeduplicate(tableEqiupSelected.value, val, "id");
}

function mergeAndDeduplicate(arr1, arr2, key) {
  const map = new Map();

  // 合并两个数组
  const combinedArray = [...arr1, ...arr2];

  // 遍历合并后的数组，并根据 key 去重
  combinedArray.forEach(item => {
    map.set(item[key], item);
  });

  // 将 Map 转换回数组
  return Array.from(map.values());
}
function deleteSelected(row) {
  tableData.value = tableData.value.filter(item => item["id"] !== row["id"]);
}

function deleteEquipSelected(row) {
  tableEqiupSelected.value = tableEqiupSelected.value.filter(item => item["id"] !== row["id"]);
}
async function getGroupListFun() {
  checkGroupList.value = await getGroupList({ name: "" });
}
const handelExecutionCycleChange = val => {
  Object.assign(formValue.value, val);
};
onBeforeMount(() => {
  scrollInit();
  getGroupListFun();
});
</script>
<style lang="scss" scoped>
.add-inspect-plan {
  display: flex;
  width: 100%;
  height: calc(100vh - 195px);
  padding: 0 24px 24px;
  overflow-x: hidden;
  background-color: #fff;
  border-radius: 8px;
  .add-inspect-plan-wrapper {
    width: calc(100% - 200px);
  }
  ._form-rules {
    :deep(.px-form-item__content) {
      flex-direction: column;
      align-items: flex-start;
    }
  }

  .add-inspect-plan-content {
    :deep(.px-form) {
      width: 100%;

      .px-form-item {
        width: 100%;
        margin-right: 0;

        .px-input {
          width: 100%;
        }

        .px-select {
          width: 100%;
        }

        .px-select-v2 {
          width: 100%;
        }

        .px-input-number {
          width: 100%;

          .px-input__inner {
            text-align: left;
          }
        }

        &.is-error {
          .px-input-number {
            .px-input__wrapper {
              border: 1px solid var(--px-color-danger);
              box-shadow: none;
            }
          }
        }
      }
    }

    .equip-table {
      --px-table-border-color: #dfdfdf;

      margin-bottom: 18px;
      font-size: 14px;

      :deep(.px-table__header) {
        thead {
          tr {
            background-color: #e7eefb !important;

            th {
              font-size: 14px;
              font-weight: bold;
              color: #000;
              background-color: #e7eefb !important;
            }
          }
        }
      }

      :deep(.px-input-number) {
        width: 100%;
      }
    }
  }

  &-wrapper {
    // flex: 1 1 auto;
    // min-width: 1350px;
  }

  .info-form-btns {
    position: absolute;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 68px;
    padding-right: 24px;
    background: #fff;
    box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
  }
}
</style>
